<?php

namespace app\admin\service;

use app\common\model\trCar;
use app\common\model\trCarList;
use app\common\model\trCarType;
use app\common\util\ErrorCode;
use app\common\util\Tools;

/**
 * Class Auth
 * @package app\admin\service
 * 车服务类
 */
class CarService
{
    private $carField = [
        "name" => "require", "model_number" => "require", "plate_number" => "require", "appearance" => "",
        "car_type" => "require", "type" => "1", "seat" => "require", "icon" => "require", "remark" => ""
    ]; //填入数据库需要存储的表字段
    private $data = [];
    private $returnData;
    private $mall_id = 0;
    private $params;

    public function __construct($data, $params = [])
    {
        $this->returnData = $data;
        $this->params = $params;
        $this->mall_id = request()->mallData["id"];
    }

    // 获取所有可用的
    public function getChoose(){
        if(!isset($this->params['type'])){
            return ErrorCode::code("params_not_exist", "type");
        }
        $model = new trCar();
        $this->returnData["data"] = $model->getList("id,name,plate_number", ["status" => 1, "car_type" => $this->params["type"], "mall_id" => $this->mall_id], 0,0, "create_time desc", false);
        return $this->returnData;
    }

    // 获取车辆的分页列表
    public function getList(){
        $page = isset($this->params['page']) ? $this->params['page'] : 1;
        $pageSize = isset($this->params['pageSize']) ? $this->params['pageSize'] : 10;
        //搜索条件
        $filter = array(["mall_id", "=", $this->mall_id]);
        if(isset($this->params['name'])){
            $filter[] = ['name', 'like', $this->params["name"] . "%"];
        }
        if(isset($this->params['carType'])){
            if(is_numeric($this->params['carType'])){
                $filter[] = ['car_type', '=', $this->params["carType"]];
            }else{
                $typeModel = new trCarType();
                $this->params["carType"] = $typeModel->getColumn("id", [["name", "like", "%{$this->params["carType"]}%"], ["mall_id", "=", $this->mall_id]]);
                $filter[] = ['car_type', 'in', $this->params["carType"]];
            }
        }
        $model = new trCar();
        $data = $model->getList("*", $filter, $page, $pageSize);
        if(!$data["data"]){
            $this->returnData['data'] = ['list' => [], 'totalPage' => $page, 'currentPage' => $page, 'count' => 0];
        }else {
            $this->returnData['data'] = ['list' => $data['data'], 'totalPage' => $data['last_page'], 'currentPage' => $data['current_page'], 'count' => $data['total']];
        }
        return $this->returnData;
    }

    // 添加车辆
    public function toAdd(){
        foreach ($this->carField as $k => $v) {
            $ks = parse_name($k); //转换字段，变驼峰
            if($v === 'require' && !isset($this->params[$ks])){
                return ErrorCode::code("params_not_exist", $ks);
            }
            $this->data[$k] = isset($this->params[$ks]) ? $this->params[$ks] : $v;
        }
        $model = new trCar();
        $id = $model->add($this->data, true);
        if(isset($id["code"])) {
            return $id;
        }
        if(!$id){
            $this->returnData = ErrorCode::$errorCode["fail"];
        }
        if(!empty($this->params["numberList"]) && !empty($numberList = @json_decode($this->params["numberList"], true))){
            foreach ($numberList as $num){
                trCarList::create(["mall_id" => $this->mall_id, "car_id" => $id, "plate_number" => $num["plateNumber"]]);
            }
        }
        return $this->returnData;
    }

    // 更新车辆
    public function toUpdate(){
        if(empty($this->params['id'])){
            return ErrorCode::code("params_not_exist", "id");
        }
        foreach ($this->carField as $k => $v) {
            $ks = parse_name($k); //转换字段，变驼峰
            if($v === 'require' && !isset($this->params[$ks])){
                return ErrorCode::code("params_not_exist", $ks);
            }
            if(isset($this->params[$ks])){
                $this->data[$k] = $this->params[$ks];
            }
        }
        $model = new trCar();
        $result = $model->doUpdate($this->data, ["id" => $this->params["id"], "mall_id" => $this->mall_id]);
        if(isset($result["code"])) {
            return $result;
        }
        if(!$result){
            $this->returnData = ErrorCode::$errorCode["fail"];
        }
        if(!empty($this->params["numberList"]) && !empty($numberList = @json_decode($this->params["numberList"], true))){
            $id = [];
            $dataId = trCarList::where(["mall_id" => $this->mall_id, "car_id" => $this->params["id"]])->column("id");
            foreach ($numberList as $num){
                if(!empty($num["id"])){
                    $id[] = $num["id"];
                    trCarList::where("id", $num["id"])->update(["plate_number" => $num["plateNumber"]]);
                }else {
                    trCarList::create(["mall_id" => $this->mall_id, "car_id" => $this->params["id"], "plate_number" => $num["plateNumber"]]);
                }
            }
            foreach (array_diff($dataId, $id) as $i){
                trCarList::where("id", $i)->delete();
            }
        }
        return $this->returnData;
    }

    // 车辆的详细内容
    public function getDetail(){
        if(empty($this->params['id'])){
            return ErrorCode::code("params_not_exist", "id");
        }
        $data = trCar::where(["id" => $this->params["id"], "mall_id" => $this->mall_id])->with([
            "numberList" => function($query){
                $query->field("car_id,plate_number,id");
        }])->find();
        if(!empty($data)){
            $data = Tools::transferFields($data->toArray());
        }else{
            $data = [];
        }
        $data["numberList"] = empty($data["numberList"]) ? [new \stdClass()] : $data["numberList"];
        $this->returnData["data"] = $data;
        return $this->returnData;
    }

    // 更新车辆状态
    public function toUpdateStatus(){
        if(empty($this->params['id'])){
            return ErrorCode::code("params_not_exist", "id");
        }

        if(!isset($this->params["status"])){
            return ErrorCode::code("params_not_exist", "status");
        }
        if(!in_array($this->params["status"], [1,2])){
            return ErrorCode::code("params_error", "status");
        }
        $this->data["status"] = $this->params["status"];

        $model = new trCar();
        $result = $model->doUpdate($this->data, ["id" => $this->params["id"], "mall_id" => $this->mall_id]);
        if(isset($result["code"])) {
            return $result;
        }
        if(!$result){
            $this->returnData = ErrorCode::$errorCode["fail"];
        }
        return $this->returnData;
    }

    // 删除车辆
    public function toDel(){
        if(empty($this->params['id'])){
            return ErrorCode::code("params_not_exist", "id");
        }
        $model = new trCar();
        $result = $model->delById($this->params['id']);
        if (isset($result["code"])) {
            return $result;
        }
        if (!$result) {
            $this->returnData = ErrorCode::$errorCode['fail'];
            $this->returnData["msg"] = "删除失败";
        }
        return $this->returnData;
    }

    public function getPlateNumber(){
        if(empty($this->params["id"])){
            return ErrorCode::code("params_not_exist", "id");
        }
        $data = trCarList::where(["car_id" => $this->params["id"], "attr_id" => 0])
            ->field("id,plate_number")
            ->select()->toArray();
        $this->returnData["data"] = Tools::transferFields($data);
        if(isset($this->params["chooseId"]) && isset($this->params["type"])){
            $data = trCarList::where(["car_id" => $this->params["id"], "attr_id" => $this->params["chooseId"], "type" => $this->params["type"]])
                ->field("id,plate_number")
                ->select()->toArray();
            $this->returnData["data"] = array_merge($this->returnData["data"], Tools::transferFields($data));
        }
        return $this->returnData;
    }
}